/*
 * SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: CC0-1.0
 */

#include <stdio.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_err.h"
#include "nvs_flash.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "bsp/esp-box-3.h"
#include "lvgl.h"

#include "app_rmker.h"
#include "app_sr.h"
#include "app_sr_tts.h"
#include "app_uvc_camera.h"
#include "app_driver.h"
#include "ui/ui.h"

#define APP_DISP_DEFAULT_BRIGHTNESS 50

static const char *TAG = "main";

esp_err_t baidu_api_key_check(void) {
    if (strcmp(CONFIG_BAIDU_API_KEY, "API_KEY") == 0 || strcmp(CONFIG_BAIDU_SECRET_KEY, "SECRET_KEY") == 0) {
        ESP_LOGE(TAG, "Please set BAIDU_API_KEY and BAIDU_SECRET_KEY to 'API' in menuconfig");
        return ESP_FAIL;
    }
    ESP_LOGI(TAG, "BAIDU_API_KEY and BAIDU_SECRET_KEY are set");
    return ESP_OK;
}

// *INDENT-OFF*
void app_lvgl_display(void)
{
    bsp_display_lock(0);

    ui_init();

    bsp_display_unlock();
}

void app_main(void)
{
    /* Initialize NVS. */
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);

    /* Check if API keys are set */
    ESP_ERROR_CHECK(baidu_api_key_check());

    /* Initialize I2C (for touch and audio) */
    ESP_ERROR_CHECK(bsp_i2c_init());

    /* Initialize display and LVGL */
    bsp_display_start();

    /* Set default display brightness */
    ESP_ERROR_CHECK(bsp_display_brightness_set(APP_DISP_DEFAULT_BRIGHTNESS));

    /* Add and show objects on display */
    app_lvgl_display();

    /* Initialize RainMaker */
    app_rmaker_start();

    /* Wait for RainMaker to connect */
    while (!app_rmaker_is_connected()) {
        vTaskDelay(1000);
    }

    /* Wait for RainMaker to setup */
    vTaskDelay(1000);

    ESP_LOGI(TAG, "============== RainMaker connected! Starting APP... ==============");
    app_sr_start();
    app_driver_init();
    app_tts_init();
    app_uvc_camera_init();
    ESP_LOGI(TAG, "Free memory after start: %d bytes", heap_caps_get_total_size(MALLOC_CAP_INTERNAL));

    while(1) {
        vTaskDelay(1000);
    }
}
